﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;


using Meqs.Entity;
using Meqs.Logic.Interface;
using Castle.Services.Transaction;
using log4net;

namespace Meqs.Logic.Implement
{
    [Transactional]
    public class GradeScoreEducationLogic : CommonLogic<GradeScoreEducation, int>, IGradeScoreEducationLogic
    {
        [Transaction(TransactionMode.RequiresNew)]
        public void GetPosition(ref int classP, ref int gradeP, ref int examP,Hashtable ht)
        {
            try
            {
                string statementName = "GradeScoreEducation.FindStudentPositionNum";
                classP = ExecuteQueryForObject<int>(statementName, ht);
                ht.Remove("ClsID");
                gradeP = ExecuteQueryForObject<int>(statementName, ht);
                ht.Remove("SchoolMark");
                examP = ExecuteQueryForObject<int>(statementName, ht);
            }
            catch (Exception ex)
            {
                ILog _log = LogManager.GetLogger("DatabaseOp");
                _log.Error("更新对象出错：" + ex.Message, ex);
                throw;
            }
        }
        public IList<SchoolExamInfo> GetSchoolScoreNum(Hashtable ht)
        {
            try
            {
                string statementName = "GradeScoreEducation.FindSchoolPositionNum";
                IList<SchoolExamInfo> schoolexaminfo = ExecuteQueryForList<SchoolExamInfo>(statementName, ht);

                foreach (SchoolExamInfo se in schoolexaminfo)
                {
                    Hashtable table = new Hashtable();
                    table.Add("TableName", ht["TableName"]);
                    table.Add("ExamID", ht["ExamID"]);
                    table.Add("SchoolMark", se.SchoolCode);
                    table.Add("Sign", ht["StrType"]);
                    table.Add("Score", ht["Score"]);

                    if (Convert.ToInt32(ht["SubjectID"]) == 0)
                    {
                        table.Add("Condition", "   ");
                    }
                    else
                    {
                        table.Add("Condition", " and subjectid= " + Convert.ToInt32(ht["SubjectID"]));
                    }
                    se.Num = ExecuteQueryForObject<int>("GradeScoreEducation.GetSchoolScoreNum", table);
                }
                ListSort<SchoolExamInfo> sort = new ListSort<SchoolExamInfo>(schoolexaminfo, "Num", false);
                schoolexaminfo = sort.Sort();
                int index = 1;
                foreach (SchoolExamInfo s in schoolexaminfo)
                {
                    s.RowIndex = index;
                    index++;
                }
                if (ht["Areaid"] != null)
                {
                    for (int i = schoolexaminfo.Count - 1; i >= 0; i--)
                    {
                        if (schoolexaminfo[i].AreaID != Convert.ToInt32(ht["Areaid"]))
                        {
                            schoolexaminfo.RemoveAt(i);
                        }
                    }
                }

                return schoolexaminfo;
            }
            catch (Exception ex)
            {
                ILog _log = LogManager.GetLogger("DatabaseOp");
                _log.Error("更新对象出错：" + ex.Message, ex);
                throw;
            }
            return null;
        }
        public IList<SchoolExamInfo> GetSchoolPositionNum(Hashtable ht)
        {
            try
            {
                string statementName = "GradeScoreEducation.FindSchoolPositionNum";
                IList<SchoolExamInfo> schoolexaminfo = ExecuteQueryForList<SchoolExamInfo>(statementName, ht); 
                Hashtable table = new Hashtable();
                if(ht["Condition"].ToString()=="desc")
                {
                    table.Add("Type", 1);
                }
                else
                {
                    table.Add("Type", 0);
                }
                if (Convert.ToInt32(ht["SubjectID"] )== 0)
                {
                    table.Add("Condition", " ");
                }
                else
                {
                    table.Add("Condition", " and subjectid = " + ht["SubjectID"].ToString() );
                }
                table.Add("TableName", ht["TableName"]);
                table.Add("ExamID", ht["ExamID"]);
                table.Add("SchoolMark", "''");

                table.Add("Number",ht["Number"].ToString());

                double positionscore = ExecuteQueryForObject<double>("GradeScoreEducation.GetStuPositionScore", table);
                foreach (SchoolExamInfo se in schoolexaminfo)
                {
                    table = new Hashtable();
                    table.Add("TableName", ht["TableName"]);
                    table.Add("ExamID", ht["ExamID"]);
                    table.Add("SchoolMark", se.SchoolCode);
                    if (ht["Condition"].ToString() == "desc")
                    {
                        table.Add("Sign", " >= ");
                    }
                    else
                    {
                        table.Add("Sign", " <= ");
                    }
                    table.Add("Score", positionscore);
                    if (Convert.ToInt32(ht["SubjectID"]) == 0)
                    {
                        table.Add("Condition", "   ");
                    }
                    else
                    {
                        table.Add("Condition", " and subjectid= " + Convert.ToInt32(ht["SubjectID"]));
                    }
                    se.Num = ExecuteQueryForObject<int>("GradeScoreEducation.GetSchoolScoreNum", table);
                }
                ListSort<SchoolExamInfo> sort = new ListSort<SchoolExamInfo>(schoolexaminfo, "Num", false);
                schoolexaminfo = sort.Sort();
                int index = 1;
                foreach (SchoolExamInfo s in schoolexaminfo)
                {
                    s.RowIndex = index;
                    index++;
                }
                if (ht["Areaid"]!=null)
                {
                    for (int i = schoolexaminfo.Count - 1; i >= 0; i--)
                    {
                        if (schoolexaminfo[i].AreaID != Convert.ToInt32(ht["Areaid"]))
                        {
                            schoolexaminfo.RemoveAt(i);
                        }
                    }
                }
                return schoolexaminfo;
            }
            catch (Exception ex)
            {
                ILog _log = LogManager.GetLogger("DatabaseOp");
                _log.Error("更新对象出错：" + ex.Message, ex);
                throw;
            }
            return null;
        }



        /// <summary>
        /// 从学校考试导入成绩
        /// </summary>
        /// <param name="educationexamid"></param>
        /// <param name="schoolexamid"></param>
        /// <param name="grade"></param>
        /// <returns>
        /// -1:考试的科目设置不一样无法导入
        /// 0：完成导入</returns>
        public int ImportScoreFromSchool(int educationexamid,string schoolmark, int schoolexamid, string tablename,int classtype)
        {
            try
            {
                string statementName = "ExamsEducation.FindById";
                ExamsEducation ee = ExecuteQueryForObject<ExamsEducation>(statementName, educationexamid);
                statementName = "ExamsSchool.FindById";
                Hashtable ht = new Hashtable();
                ht.Add("SchoolMark", schoolmark);
                ht.Add("RID", schoolexamid);
                ExamsSchool es = ExecuteQueryForObject<ExamsSchool>(statementName, ht);

                ht = new Hashtable();
                ht.Add("SchoolMark", schoolmark);
                ht.Add("ExamID", schoolexamid);
                statementName = "ExamSubjecySchool.Find";
                IList<ExamSubjecySchool> schoolsubject = ExecuteQueryForList<ExamSubjecySchool>(statementName, ht);



                ht = new Hashtable();
                ht.Add("ExamID", educationexamid);
                statementName = "ExamSubjecyEducation.Find";
                IList<ExamSubjecyEducation> edusubject = ExecuteQueryForList<ExamSubjecyEducation>(statementName, ht);
                //判断设定的科目不匹配
                if (schoolsubject.Count != edusubject.Count)
                {
                    return -1;
                }

                foreach (ExamSubjecySchool r in schoolsubject)
                {
                    if (!InEdu(edusubject, r.SubjectID))
                    {
                        return -1;
                    }
                }

                //可以导入了。
                statementName = "ExamDetailSchool.Find";
                ht = new Hashtable();
                ht.Add("ExamID", schoolexamid);
                ht.Add("SchoolMark", schoolmark);
                IList<ExamDetailSchool> detail = ExecuteQueryForList<ExamDetailSchool>(statementName, ht);

                ht = new Hashtable();
                ht.Add("SchoolMark", schoolmark);
                ht.Add("ExamID", educationexamid);
                ht.Add("TableName", tablename);
                DeleteOneClassScoreForExam(ht);

                foreach (ExamDetailSchool d in detail)
                {
                    GradeScoreEducation gs = new GradeScoreEducation();
                    gs.ClsID = d.ClsID;
                    gs.ExamID = educationexamid;
                    gs.SchoolMark = schoolmark;
                    gs.Score = d.Score;
                    gs.StudentID = d.StudentID;
                    gs.SubjectID = d.SubjectID;
                    gs.TableName = tablename;
                    gs.Type = classtype;
                    Create(gs);
                }

                ht = new Hashtable();
                ht.Add("SchoolMark", schoolmark);
                ht.Add("ExamID", educationexamid);
                statementName = "ExamClassEducation.DeleteSchool";
                ExecuteDelete(statementName, ht);

                ht = new Hashtable();
                ht.Add("ExamID", schoolexamid);
                ht.Add("SchoolMark", schoolmark);
                statementName = "ExamClassSchool.Find";
                IList<ExamClassSchool> ecs = ExecuteQueryForList<ExamClassSchool>(statementName, ht);
                foreach (ExamClassSchool cc in ecs)
                {
                    ExamClassEducation eclass = new ExamClassEducation();
                    eclass.ClassID = cc.SchoolClassID;
                    eclass.ExamID = educationexamid;
                    eclass.SchoolMark = schoolmark;
                    eclass.Status = 0;
                    ExecuteInsert("ExamClassEducation.Insert", eclass);
                }
                statementName = "ExamDetailSchool.Delete";
                es.SchoolMark = schoolmark;
                ExecuteDelete(statementName, es);

                statementName = "ExamsSchool.Delete";
                ht = new Hashtable();
                ht.Add("RID", schoolexamid);
                ht.Add("SchoolMark", schoolmark);
                ExecuteDelete(statementName, es);

                ht = new Hashtable();
                ht.Add("TestID", educationexamid);
                statementName = "GradeScoreEducation.UpdateCatch";
                ExecuteUpdate(statementName, ht);
            }
            catch (Exception ex)
            {
                ILog _log = LogManager.GetLogger("DatabaseOp");
                _log.Error("更新对象出错：" + ex.Message, ex);
                throw;
            }
            return 0;
        }
        private bool InEdu(IList<ExamSubjecyEducation> edusubject,int subjectid)
        {
            foreach (ExamSubjecyEducation es in edusubject)
            {
                if (es.SubjectID == subjectid)
                {
                    return true;
                }
            }
            return false;
        }
        //BatchSave<GradeScoreEducation>("GradeScoreEducation", IList<GradeScoreEducation> objArray)
        [Transaction(TransactionMode.RequiresNew)]
        public int SaveStudentScores(int[] stuids, int[] subjectids, double[] scores, int emid,  int clsType,int clsid,string tablename,string schoolmark)
        {

            List<GradeScoreEducation> list = new List<GradeScoreEducation>();
            string ids = "(0";
            for (int i = 0; i < stuids.Length;i++ )
            {
                ids += "," + stuids[i];
                for (int j = 0; j < subjectids.Length; j++)
                {
                    GradeScoreEducation ge = new GradeScoreEducation();
                    ge.StudentID = stuids[i];
                    ge.SubjectID = subjectids[j];
                    ge.TableName = tablename;
                    ge.SchoolMark = schoolmark;
                    ge.Type = clsType;
                    ge.ExamID = emid;
                    ge.ClsID = clsid;
                    ge.Score = null;
                    if (scores[i * subjectids.Length + j] != -1)
                    {
                        ge.Score = scores[i * subjectids.Length + j];
                    }
                    
                    
                    list.Add(ge);
                }
            }
            ids += ")";
            Hashtable table = new Hashtable();
            table.Add("SchoolMark", schoolmark);
            table.Add("ExamID", emid);
            table.Add("Studentid", ids);
            table.Add("TableName", tablename);
            table.Add("ClsID", clsid);
            DeleteOneClassScoreForExam(table);
            foreach (GradeScoreEducation gs in list)
            {
                Create(gs);
            }
            ExamClassEducation eclass = new ExamClassEducation();
            eclass.ClassID = clsid;
            eclass.ExamID = emid;
            eclass.SchoolMark = schoolmark;
            eclass.Status = 1;


            table = new Hashtable();
            table.Add("ClassID", clsid);
            table.Add("ExamID", emid);
            table.Add("SchoolMark", schoolmark);

            IList<ExamClassEducation> tc = FindCustomer<ExamClassEducation>("ExamClassEducation.Find", table);
            if (tc.Count == 0)
            {
                ExecuteInsert("ExamClassEducation.Insert", eclass);
            }
            
            //更新相关考试的相关班级,目前指更新统考分数线，和年级前×名
            table = new Hashtable();
            table.Add("ClassID", clsid);
            table.Add("TestID", emid);
            table.Add("SchoolMark", schoolmark);
            try
            {
                string statementName = "GradeScoreEducation.UpdateCatch";
                ExecuteUpdate(statementName, table);

                table = new Hashtable();
                table.Add("ClassID", clsid);
                table.Add("SchoolMark", schoolmark);
                statementName = "ExamTeachEducation.FindCount";
                int count = ExecuteQueryForObject<int>(statementName, table);
                if (count <= 0)
                {
                    table = new Hashtable();
                    table.Add("ClsID", clsid);
                    statementName = "TeachClsCause.Find";
                    IList<TeachClsCause> l = ExecuteQueryForList<TeachClsCause>(statementName, table);
                    foreach (TeachClsCause t in l)
                    {
                        ExamTeachEducation et = new ExamTeachEducation(0, emid, t.CauseID, t.TeachID, clsid, schoolmark);
                        statementName = "ExamTeachEducation.Insert";
                        ExecuteInsert(statementName, et);
                    }
                }

            }
            catch (Exception ex)
            {
                ILog _log = LogManager.GetLogger("DatabaseOp");
                _log.Error("更新对象出错：" + ex.Message, ex);
                throw;
            }
            //return BatchSave<GradeScoreEducation>("GradeScoreEducation.Insert", list);
            return 0;
        }

        private  int DeleteOneClassScoreForExam(Hashtable ht)
        {
            try
            {
                string statementName = "GradeScoreEducation.DeleteOneClassScoreForExam";
                return ExecuteDelete(statementName, ht);
            }
            catch (Exception ex)
            {
                ILog _log = LogManager.GetLogger("DatabaseOp");
                _log.Error("删除全部对象出错：" + ex.Message, ex);
                throw;
            }
        }
        #region Implementation of ICommonLogic<GradeScoreEducation, int>

        /// <sammury>
        /// 创建对象
        /// </sammury>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Create(GradeScoreEducation entity)
        {
            
            return CreateObject(entity);
        }

        /// <sammury>
        /// 更新对象
        /// </sammury>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update(GradeScoreEducation entity)
        {
            return UpdateObject(entity);
        }

        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public int Delete(int entityId)
        {
            return DeleteObject(entityId);
        }

        /// <summary>
        /// 删除所有对象
        /// </summary>
        /// <returns></returns>
        public int DeleteAll()
        {
            return DeleteAllObject();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public GradeScoreEducation FindById(int entityId)
        {
            return FindObjectById(entityId);
        }

        /// <summary>
        /// 检索对象数量
        /// </summary>
        /// <returns></returns>
        public int FindCount()
        {
            return FindObjectByCount();
        }

        /// <sammury>
        /// 检索对象
        /// </sammury>
        public IList<GradeScoreEducation> FindAll()
        {
            return FindAllObject();
        }

        /// <summary>
        /// 检索对象数量
        /// </summary>
        /// <returns></returns>
        public int FindCount(Hashtable table)
        {
            return FindObjectByCount(table);
        }

        /// <sammury>
        /// 检索对象
        /// </sammury>
        public IList<GradeScoreEducation> FindAll(Hashtable table)
        {
            return FindObject(table);
        }

        #endregion
    }
}